# -*- coding: utf-8 -*-
# © 2017 Jarvis (Odoo模块网 odoomk.com)
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).

from odoo import api, models, _,fields


class SaleOrder(models.Model):
    _inherit = 'sale.order'

    purchase_count = fields.Integer(compute="_compute_purchase", string='#个采购订单', copy=False, default=0)
    purchase_ids = fields.Many2many('purchase.order', compute="_compute_purchase", string='采购订单', copy=False)

    @api.multi
    def action_view_purchase(self):
        purchase_ids = self.mapped('purchase_ids')
        imd = self.env['ir.model.data']
        action = imd.xmlid_to_object('purchase.purchase_form_action')
        list_view_id = imd.xmlid_to_res_id('purchase.purchase_order_tree')
        form_view_id = imd.xmlid_to_res_id('purchase.purchase_order_from')

        result = {
            'name': action.name,
            'help': action.help,
            'type': action.type,
            'views': [[list_view_id, 'tree'], [form_view_id, 'form'], [False, 'graph'], [False, 'kanban'], [False, 'calendar'], [False, 'pivot']],
            'target': action.target,
            'context': action.context,
            'res_model': action.res_model,
        }
        if len(purchase_ids) > 1:
            result['domain'] = "[('id','in',%s)]" % purchase_ids.ids
        elif len(purchase_ids) == 1:
            result['views'] = [(form_view_id, 'form')]
            result['res_id'] = purchase_ids.ids[0]
        else:
            result = {'type': 'ir.actions.act_window_close'}
        return result

    @api.depends('procurement_group_id.procurement_ids')
    def _compute_purchase(self):
        for order in self:
            purchases = self.env['purchase.order']
            for procurement_id in order.procurement_group_id.procurement_ids:
                if procurement_id.purchase_id.state != 'cancel':
                    purchases |= procurement_id.mapped('purchase_id')
            order.purchase_ids = purchases
            order.purchase_count = len(purchases)
